package com.open.cloud.rbac.service.role.impl;

import cn.hutool.core.lang.Snowflake;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.open.cloud.rbac.entity.orgpost.CoreRoleOrgRel;
import com.open.cloud.rbac.entity.orgpost.CoreRolePostRel;
import com.open.cloud.rbac.entity.permission.CorePermission;
import com.open.cloud.rbac.entity.role.CoreRole;
import com.open.cloud.rbac.entity.role.CoreRolePermissionRel;
import com.open.cloud.rbac.entity.role.CoreRoleUserRel;
import com.open.cloud.rbac.mapper.orgpost.CoreRoleOrgRelMapper;
import com.open.cloud.rbac.mapper.orgpost.CoreRolePostRelMapper;
import com.open.cloud.rbac.mapper.role.CoreRoleMapper;
import com.open.cloud.rbac.mapper.role.CoreRolePermissionRelMapper;
import com.open.cloud.rbac.mapper.role.CoreRoleUserRelMapper;
import com.open.cloud.rbac.object.role.*;
import com.open.cloud.rbac.service.role.ICoreRoleService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author wangzengzhou01
 * @since 2024-12-23
 */
@Service
public class CoreRoleServiceImpl extends ServiceImpl<CoreRoleMapper, CoreRole>
        implements ICoreRoleService {

    @Resource
    private CoreRoleMapper roleMapper;

    @Resource
    private Snowflake snowflake;

    @Resource
    private CoreRolePermissionRelMapper rolePermissionRelMapper;

    @Resource
    private CoreRolePostRelMapper rolePostRelMapper;

    @Resource
    private CoreRoleOrgRelMapper roleOrgRelMapper;

    @Resource
    private CoreRoleUserRelMapper roleUserRelMapper;

    /**
     * 新增角色信息
     *
     * @param roleDto
     * @return
     */
    @Override
    public JSONObject addRoleInfo(CoreRoleDto roleDto) {
        CoreRole role = new CoreRole();
        BeanUtils.copyProperties(roleDto, role);
        role.setId(snowflake.nextIdStr());
        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        int i = roleMapper.insert(role);
        JSONObject result = new JSONObject();
        if (i > 0) {
            result.put("code", 200);
            result.put("message", "创建成功");
        } else {
            result.put("code", 500);
            result.put("message", "创建失败");
        }
        return result;
    }

    /**
     * 更新角色信息
     *
     * @param roleDto
     * @return
     */
    @Override
    public JSONObject updateRoleInfo(CoreRoleDto roleDto) {
        CoreRole role = new CoreRole();
        BeanUtils.copyProperties(roleDto, role);
        role.setUpdateTime(new Date());
        int i = this.baseMapper.updateById(role);
        JSONObject resultObj = new JSONObject();
        if (i > 0) {
            resultObj.put("code", 200);
            resultObj.put("message", "修改成功");
        } else {
            resultObj.put("code", 500);
            resultObj.put("message", "修改失败");
        }
        return resultObj;
    }

    /**
     * 删除角色信息
     *
     * @param roleId
     * @param isForce
     * @return
     */
    @Override
    public JSONObject deleteRoleInfo(String roleId, Boolean isForce) {
        JSONObject result = new JSONObject();
        LambdaQueryWrapper permissionRelQuery = Wrappers.<CoreRolePermissionRel>lambdaQuery()
                .eq(CoreRolePermissionRel::getRoleId, roleId);

        LambdaQueryWrapper userRelQuery = Wrappers.<CoreRoleUserRel>lambdaQuery()
                .eq(CoreRoleUserRel::getRoleId, roleId);

        LambdaQueryWrapper orgRelQuery = Wrappers.<CoreRoleOrgRel>lambdaQuery()
                .eq(CoreRoleOrgRel::getRoleId, roleId);

        LambdaQueryWrapper postRelQuery = Wrappers.<CoreRolePostRel>lambdaQuery()
                .eq(CoreRolePostRel::getRoleId, roleId);
        if (isForce) {
            rolePermissionRelMapper.delete(permissionRelQuery);
            roleUserRelMapper.delete(userRelQuery);
            roleOrgRelMapper.delete(orgRelQuery);
            rolePostRelMapper.delete(postRelQuery);
            int i = this.baseMapper.deleteById(roleId);
            if (i > 0) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除失败");
            }
        } else {
            List permissionRelList = rolePermissionRelMapper.selectList(permissionRelQuery);

            List userRelList = roleUserRelMapper.selectList(userRelQuery);

            List orgRelList = roleOrgRelMapper.selectList(orgRelQuery);

            List postRelList = rolePostRelMapper.selectList(postRelQuery);

            if (permissionRelList.size() > 0 || userRelList.size() > 0 || orgRelList.size() > 0 || postRelList.size() > 0) {
                String message = "该角色信息下存在关联";
                if (permissionRelList.size() > 0) {
                    message += "权限，";
                }
                if (userRelList.size() > 0) {
                    message += "用户，";
                }
                if (orgRelList.size() > 0) {
                    message += "部门，";
                }
                if (postRelList.size() > 0) {
                    message += "岗位，";
                }
                result.put("code", 510);
                result.put("message", message + "删除失败");
            } else {
                int i = this.baseMapper.deleteById(roleId);
                if (i > 0) {
                    result.put("code", 200);
                    result.put("message", "删除成功");
                } else {
                    result.put("code", 500);
                    result.put("message", "删除失败");
                }
            }
        }
        return result;
    }

    /**
     * 根据条件分页查询角色信息
     *
     * @param selectDto
     * @return
     */
    @Override
    public IPage<CoreRoleVo> getRolePage(CoreRoleSelectDto selectDto) {
        QueryWrapper<CoreRole> queryWrapper = Wrappers.<CoreRole>query()
                .orderByDesc("cr.role_sort");
//                .eq(ObjectUtils.isNotEmpty(selectDto.getPageNo()))
        IPage<CoreRole> page = new Page<>(selectDto.getPageNo(), selectDto.getPageSize());
        IPage<CoreRoleVo> data = roleMapper.selectRoleByPage(page, queryWrapper);
        return data;
    }

    /**
     * 获取角色列表
     *
     * @param selectDto
     * @return
     */
    @Override
    public List<CoreRole> getRoleList(CoreRoleSelectDto selectDto) {
        QueryWrapper<CoreRole> queryWrapper = Wrappers.<CoreRole>query()
                .orderByDesc("role_sort");
        List<CoreRole> roleList = roleMapper.selectList(queryWrapper);
        return roleList;
    }

    /**
     * 根据角色Id 获取权限关联列表
     *
     * @param roleId
     * @return
     */
    @Override
    public List<CoreRolePermissionRel> getRolePermissionRelList(String roleId) {
        LambdaQueryWrapper permissionRelQuery = Wrappers.<CoreRolePermissionRel>lambdaQuery()
                .eq(CoreRolePermissionRel::getRoleId, roleId);
        List permissionRelList = rolePermissionRelMapper.selectList(permissionRelQuery);
        return permissionRelList;
    }

    /**
     * 设置角色权限关联
     *
     * @param rolePermissionDto
     * @return
     */
    @Override
    public JSONObject setRolePermissionRel(CoreRolePermissionDto rolePermissionDto) {
        Boolean isCheck = rolePermissionDto.getIsCheck();
        JSONObject result = new JSONObject();
        Integer count = 0;
        if (isCheck) {
            ArrayList<CoreRolePermissionRel> list = new ArrayList<>();
            List<CorePermission> permissionList = rolePermissionDto.getPermissionList();
            permissionList.forEach(item -> {
                CoreRolePermissionRel rolePermissionRel = new CoreRolePermissionRel();
                rolePermissionRel.setId(snowflake.nextIdStr());
                rolePermissionRel.setRoleId(rolePermissionDto.getRoleId());
                rolePermissionRel.setPermissionId(item.getId());
                rolePermissionRel.setCreateTime(new Date());
                list.add(rolePermissionRel);
            });
            count = rolePermissionRelMapper.batchInsertRolePermissionRel(list);
        } else {
            count = rolePermissionRelMapper.deletePermissionMenuRel(rolePermissionDto.getRoleId(), rolePermissionDto.getPermissionList());
        }
        if (count > 0) {
            result.put("code", 200);
            result.put("message", "设置成功");
        } else {
            result.put("code", 500);
            result.put("message", "设置失败");
        }
        return result;
    }

    /**
     * 根据orgId查询关联Role列表
     *
     * @param orgId
     * @return
     */
    @Override
    public List<String> getOrgRelRoleByOrgId(String orgId) {
        List<String> roleIds = roleOrgRelMapper.selectRoleIdByOrgId(orgId);
        return roleIds;
    }

    /**
     * 组织分配角色
     *
     * @param roleOrgRelDto
     * @return
     */
    @Override
    public JSONObject setOrgRelRole(CoreRoleOrgRelDto roleOrgRelDto) {
        LambdaQueryWrapper<CoreRoleOrgRel> queryWrapper = Wrappers.<CoreRoleOrgRel>lambdaQuery()
                .eq(CoreRoleOrgRel::getOrgId, roleOrgRelDto.getOrgId());
        int count = roleOrgRelMapper.delete(queryWrapper);
        ArrayList<CoreRoleOrgRel> list = new ArrayList<>();
        List<CoreRole> roleList = roleOrgRelDto.getRoleList();
        if (roleList.size() > 0) {
            roleList.forEach(item -> {
                CoreRoleOrgRel roleOrgRel = new CoreRoleOrgRel();
                roleOrgRel.setId(snowflake.nextIdStr());
                roleOrgRel.setOrgId(roleOrgRelDto.getOrgId());
                roleOrgRel.setRoleId(item.getId());
                roleOrgRel.setCreateTime(new Date());
                list.add(roleOrgRel);
            });
            count = roleOrgRelMapper.batchInsertOrgRoleRel(list);
        }

        JSONObject result = new JSONObject();
        if (count > 0) {
            result.put("code", 200);
            result.put("message", "设置成功");
        } else {
            result.put("code", 500);
            result.put("message", "设置失败");
        }
        return result;
    }

    /**
     * 根据postId获取角色Ids
     *
     * @param postId
     * @return
     */
    @Override
    public List<String> getRoleIdsRelPostByPostId(String postId) {
        List<String> list = rolePostRelMapper.selectRoleIdByPostId(postId);
        return list;
    }

    /**
     * 岗位分配角色
     *
     * @param postRelDto
     * @return
     */
    @Override
    public JSONObject setPostRelRole(CoreRolePostRelDto postRelDto) {
        LambdaQueryWrapper<CoreRolePostRel> queryWrapper = Wrappers.<CoreRolePostRel>lambdaQuery()
                .eq(CoreRolePostRel::getPostId, postRelDto.getPostId());
        int count = rolePostRelMapper.delete(queryWrapper);
        ArrayList<CoreRolePostRel> list = new ArrayList<>();
        List<CoreRole> roleList = postRelDto.getRoleList();
        if (roleList.size() > 0) {
            roleList.forEach(item -> {
                CoreRolePostRel rolePostRel = new CoreRolePostRel();
                rolePostRel.setId(snowflake.nextIdStr());
                rolePostRel.setPostId(postRelDto.getPostId());
                rolePostRel.setRoleId(item.getId());
                rolePostRel.setCreateTime(new Date());
                list.add(rolePostRel);
            });
            count = rolePostRelMapper.batchInsertPostRoleRel(list);
        }

        JSONObject result = new JSONObject();
        if (count > 0) {
            result.put("code", 200);
            result.put("message", "设置成功");
        } else {
            result.put("code", 500);
            result.put("message", "设置失败");
        }
        return result;
    }

    /**
     * 根据userId获取角色Ids
     *
     * @param userId
     * @return
     */
    @Override
    public List<String> getRoleIdsRelUserByUserId(String userId) {
        List<String> list = roleUserRelMapper.selectRoleIdByUserId(userId);
        return list;
    }

    /**
     * 用户分配角色
     *
     * @param userRelDto
     * @return
     */
    @Override
    public JSONObject setUserRelRole(CoreRoleUserRelDto userRelDto) {
        LambdaQueryWrapper<CoreRoleUserRel> queryWrapper = Wrappers.<CoreRoleUserRel>lambdaQuery()
                .eq(CoreRoleUserRel::getUserId, userRelDto.getUserId());
        int count = roleUserRelMapper.delete(queryWrapper);
        ArrayList<CoreRoleUserRel> list = new ArrayList<>();
        List<CoreRole> roleList = userRelDto.getRoleList();
        if (roleList.size() > 0) {
            roleList.forEach(item -> {
                CoreRoleUserRel roleUserRel = new CoreRoleUserRel();
                roleUserRel.setId(snowflake.nextIdStr());
                roleUserRel.setUserId(userRelDto.getUserId());
                roleUserRel.setRoleId(item.getId());
                roleUserRel.setCreateTime(new Date());
                list.add(roleUserRel);
            });
            count = roleUserRelMapper.batchInsertUserRoleRel(list);
        }

        JSONObject result = new JSONObject();
        if (count > 0) {
            result.put("code", 200);
            result.put("message", "设置成功");
        } else {
            result.put("code", 500);
            result.put("message", "设置失败");
        }
        return result;
    }

}
